//初始化
var airports="";
var biid="";
var giid="";
var pics=[];
var flag=1;
var idNum=10000;
var handle="";
var goodsSmallCategories=[];
var skuFlag="";
var skuId="";
var skuIndex="";
var skuBreak=1;
var saveFlag=1;

function split(data){
    if(data==null){
        return "";
    }else{
        return data.split(",");
    }
}

//ueditor配置
var ue = UE.getEditor('editor');
UE.Editor.prototype._bkGetActionUrl = UE.Editor.prototype.getActionUrl;
UE.Editor.prototype.getActionUrl = function (action) {
    //这里很重要，很重要，很重要，要和配置中的imageActionName值一样
    if (action == 'fileUploadServlet') {
        //这里调用后端我们写的图片上传接口
        return web_url_prefix + "upload/uploadImageUeditorMulit"
    } else {
        return this._bkGetActionUrl.call(this, action);
    }
};

$(document).ready(function(){
        //商品大小类分类
    ajax({
        url:"goods/queryGoodsSizeClasses",
        data:{},
        success:function(data){
            
            if(data.success){
                classify(data);
                //跳转进入
                if(getStorJson("jumpToGoodsAdd")!=null){
                    var msg=getStorJson("jumpToGoodsAdd");
                    giid=msg.giid;
                    biid=msg.biid;
                    handle=msg.handle;
                    delete window.localStorage.jumpToGoodsAdd;
                    //商品类型
                    ajax({
                        url:"goods/queryGoodsCategory",
                        data:{biid:biid},
                        success:function(data){
                            if(data.success){
                                var html = template("styleTemplate",data);
                                document.getElementById('goodsStyle').innerHTML = html;
                                //请求后放入商品数据
                                ajax({
                                    url:"goods/goodsDetailShow",
                                    data:{
                                        giid:giid
                                    },
                                    success:function(data){
                                        
                                        if(data.success){
                                            goodsMsg(data);
                                        }else{
                                            layer.msg(data.massage)
                                        }
                                    }
                                });
                            }else{
                                layer.msg(data.message)
                            }
                        }
                    });
                }
            }else{
                layer.msg(data.message)
            }
        }
    });


    $(".filelist").on("click",".changeMainPic",function(){
            $(".allPic").removeClass("mainPic").addClass("otherPic");
            $(this.parentNode.previousElementSibling.previousElementSibling.children).addClass("mainPic").removeClass("otherPic");
            $(".filelist li").removeClass("mainLi");
            $(this.parentNode.parentNode).addClass("mainLi");
    }).on("mouseenter",".changeMainPic",function(){
        $(this).removeClass("changeMainPicture").addClass("textChangeMainPic");
    }).on("mouseleave",".changeMainPic",function(){
        $(this).addClass("changeMainPicture").removeClass("textChangeMainPic");
    }).on("click",".canceled",function(){
        $(this.parentNode.parentNode).remove();
    });

    //保存
    $("#saveGoods").click(function(){
        if(saveFlag!==1){
            layer.msg("请不要重复提交");
            return;
        }
        saveFlag=0;
        if(handle=="copy"){
            giid="";
        }
        if($('.otherPic').length>8){
            layer.msg("图片集不能超过八张");
            saveFlag=1;
            return;
        }
        var goodsName=$("#goodsName").val();
        if(goodsName==""){
            layer.msg("请输入商品名称");
            saveFlag=1;
            return;
        }
        var gMainPic=$(".mainPic").attr("data-url");
        if(gMainPic==""||gMainPic==undefined){
            layer.msg("请设置主图");
            saveFlag=1;
            return;
        }
        var picture=[];
        var otherPic=$(".otherPic");
        for(var i=0;i<otherPic.length;i++){
           var pic= $(otherPic[i]).attr("data-url");
            picture.push(pic)
        }
        var gsid=$("#goodsSmallCategories").val();
        if(gsid==""){
            layer.msg("请选择商品小类");
            saveFlag=1;
            return;
        }
        var gcid=$("#goodsLargeCategories").val();
        var goodsSlogan=$("#goodsSlogan").val();
        if(goodsSlogan==""){
            layer.msg("请输入广告语");
            saveFlag=1;
            return;
        }
        var ccid=$("#goodsStyle").val();
        if(ccid==""){
            layer.msg("请选择商品品类");
            saveFlag=1;
            return;
        }

        var goodsLabel="";
        if($("#goodsTab").val()!=null){
            goodsLabel=$("#goodsTab").val().join(",");
        }
        var dmids="";
        if($("#deliveryType").val()!=null){
            dmids=$("#deliveryType").val().join(",");
        }
        var supplierId=$("#supplier").attr("data-supplierId");
        var introduction = UE.getEditor('editor').getContent();
        var goodsSkuVOList=[];
        var sku=$(".tr");
        for(var j=0;j<sku.length;j++){
            var gskuid=$(sku[j]).attr("data-sku");
            var skupic=$(sku[j]).attr("data-url");
            if(skupic==""){
                layer.msg("SKU图片异常");
                saveFlag=1;
                return;
            }
            var gsOptions=sku[j].lastElementChild.previousElementSibling.innerHTML;
            var agreementPrice=sku[j].lastElementChild.previousElementSibling.previousElementSibling.previousElementSibling.innerHTML;
            if(agreementPrice==""){
                layer.msg("SKU结算价不能为空");
                saveFlag=1;
                return;
            }
            var availableInventory=sku[j].lastElementChild.previousElementSibling.previousElementSibling.innerHTML;
            var retailPrice=sku[j].firstElementChild.nextElementSibling.nextElementSibling.innerHTML;
            var marketPrice=sku[j].firstElementChild.nextElementSibling.innerHTML;
            var oneSku={
                gskuId:gskuid,
                skupic:skupic,
                gsOptions:gsOptions,
                agreementPrice:agreementPrice,
                availableInventory:availableInventory,
                retailPrice:retailPrice,
                marketPrice:marketPrice
            };
            goodsSkuVOList.push(oneSku);
        }
        var skuListString=JSON.stringify(goodsSkuVOList);
        ajax({
            url:"goods/goodsAddOrUpdate",
            traditional: true,
            type:"post",
            dataType:"json",
            data:{
                //商户id
                biid:biid,
                //    商品id
                giid:giid,
                //    商品名称
                goodsName:goodsName,
                //    商品主图
                gMainPic:gMainPic,
                // 商品图片
                picture:picture,
                // 图文详情
                gIntroduction:introduction,
                //    商品大类
                gcid:gcid,
                //    商品子类id
                gsid:gsid,
                //    供应商
                supplierId:supplierId,
                //    店铺分类
                ccid:ccid,
                //    多个商品SKU
                skuListString:skuListString,
                //    商品标签
                goodsLabel:goodsLabel,
                //    商品广告语
                goodsSlogan:goodsSlogan,
                //    配送方式
                dmids:dmids
            },
            success:function(data){
                
                if(data.success){
                    layer.msg("保存成功");
                    window.location.href="goods.html";
                }else{
                    saveFlag=1;
                    layer.msg(data.message)
                }
            }
        })
    })
});
    //处理大小分类
    function classify(data){
        var goodsLargeCategories="";
        var largeCategories=data.data.sizeTinyCategories;
        for(var i=0;i<largeCategories.length;i++){
            goodsLargeCategories+='<option value="'+largeCategories[i].GCID+'">'+largeCategories[i].goodsCategories+'</option>';
            goodsSmallCategories.push(largeCategories[i].subclassList)
        }
        $("#goodsLargeCategories").html(goodsLargeCategories).change(function(){
            var index=this.selectedIndex;
            var html="";
            for(var j=0;j<goodsSmallCategories[index].length;j++){
                html+='<option value="'+goodsSmallCategories[index][j].gsid+'">'+goodsSmallCategories[index][j].gsname+'</option>';
            }
            $("#goodsSmallCategories").html(html);
        });
        var optionHtml="<option value=''>全部</option>";
        for(var j=0;j<goodsSmallCategories[0].length;j++){
            optionHtml+='<option value="'+goodsSmallCategories[0][j].gsid+'">'+goodsSmallCategories[0][j].gsname+'</option>';
        }
        $("#goodsSmallCategories").html(optionHtml);
        var goodsLabel=data.data.goodsLabel;
        var goodsLabelHtml="";
        if(goodsLabel!=null||goodsLabel!=""){
            for(var l=0;l<goodsLabel.length;l++){
                goodsLabelHtml+='<option value="'+goodsLabel[l].label_id+'">'+goodsLabel[l].label_name+'</option>';
            }
            $("#goodsTab").html(goodsLabelHtml).selectpicker('refresh');
            // $('.selectpicker').selectpicker('refresh');
        }
        //配送方式
        var goodsDeliveryMethod=data.data.goodsDeliveryMethod;
        var deliveryTypeHtml="";
        if(goodsDeliveryMethod.length>0){
            for(var m=0;m<goodsDeliveryMethod.length;m++){
                deliveryTypeHtml+='<option value="'+goodsDeliveryMethod[m].dmid+'">'+goodsDeliveryMethod[m].dmname+'</option>';
            }
            $("#deliveryType").html(deliveryTypeHtml).selectpicker('refresh');
        }
    }
//    处理商品信息
    function goodsMsg(data) {
        if(handle=="edit"){
            $("#connectShop").attr("disabled","disabled");
        }
        if(data.data.goodsLabel!=""){
            $("#goodsTab").selectpicker("val",split(data.data.goodsLabel));
        }
        if(data.data.dmids!=""){
            $("#deliveryType").selectpicker("val",split(data.data.dmids));
        }
        if(!isNULL(data.data.supplierId)){
            $("#supplier").val(data.data.supplierName).attr("data-supplierId",data.data.supplierId);
        }
        $("#goodsName").val(data.data.goodsName);
        $("#pic1").attr("src",changeImgUrl(data.data.gMainPic)).attr("data-url",data.data.gMainPic);
        $("#goodsStyle").val(data.data.ccid);
        $("#connectShop").val(data.data.biName).attr("data-biid",data.data.biid);
        //接口调整后增加
        $("#goodsSlogan").val(data.data.goodsSlogan);
        $("#goodsLargeCategories").val(data.data.gcid);
        var goodsIndex=$("#goodsLargeCategories")[0].selectedIndex;
        var goodsHtml="";
        for(var k=0;k<goodsSmallCategories[goodsIndex].length;k++){
            goodsHtml+='<option value="'+goodsSmallCategories[goodsIndex][k].gsid+'">'+goodsSmallCategories[goodsIndex][k].gsname+'</option>';
        }
        $("#goodsSmallCategories").html(goodsHtml).val(data.data.gsid);
        ue.setContent(data.data.gIntroduction);
        var mainPic='<li id='+"WU_FILE_"+idNum+' class="state-complete mainLi">' +
            '<p class="title"> </p>' +
            '<p class="imgWrap">' +
            '<img src="'+changeImgUrl(data.data.gMainPic)+'" data-url="'+data.data.gMainPic+'" class="'+"allPic mainPic previewImg"+'">' +
            '</p>' +
            '<p class="progress"><span style="display: none; width: 0;"></span></p>' +
            '<div class="file-panel file-paneled" style="height: 0;">' +
            '<span class="cancel canceled">删除</span>' +
            '<span class="changeMainPic changeMainPicture">设为主图</span>' +
            '</div>' +
            '<span class="success"></span>' +
            '</li>';
        idNum++;
        $(".filelist").append(mainPic);
        previewImg();
        var list=data.data.goodsSkuVOList;
        var showPic=data.data.picture;
        var allPic="";
        for(var j=0;j<showPic.length;j++){
            if(isNULL(showPic[j]))continue;
            allPic+='<li id='+"WU_FILE_"+idNum+' class="state-complete">' +
                '<p class="title"></p>' +
                '<p class="imgWrap">' +
                '<img src="'+changeImgUrl(showPic[j])+'" data-url="'+showPic[j]+'" class="'+"allPic otherPic previewImg"+'">' +
                '</p>' +
                '<p class="progress"><span style="display: none; width: 0;"></span></p>' +
                '<div class="file-panel file-paneled" style="height: 0;">' +
                '<span class="cancel canceled">删除</span>' +
                '<span class="changeMainPic changeMainPicture">设为主图</span>' +
                '</div>' +
                '<span class="success"></span>' +
                '</li>';
            idNum++;
        }
        var html="";
        for(var i=0;i<list.length;i++){
            var agreementPrice="";
            if(list[i].agreementPrice!=null){
                agreementPrice=list[i].agreementPrice;
            }
            html+="<tr data-url='"+list[i].skupic+"' data-sku='"+list[i].gskuId+"' class="+"tr"+">"
                +"<td><img src='"+changeImgUrl(list[i].skupic)+"' class='previewImg'></td>"
                +"<td>"+list[i].marketPrice+"</td>"
                +"<td>"+list[i].retailPrice+"</td>"
                +"<td>"+agreementPrice+"</td>"
                +"<td>"+list[i].availableInventory+"</td>"
                +"<td>"+list[i].gsOptions+"</td>"
                +"<td><div><a class='editSku'>编辑</a></div><div><a class='deleteSku'>删除</a></div></td>"
                +"</tr>";
        }
        $("#tbody").append(html);
        $(".filelist").append(allPic);
        previewImg();
        $(".filelist>li").on( 'mouseenter', function() {
            $(this).find(".file-paneled").stop().animate({height: 30});
        }).on( 'mouseleave', function() {
                $(this).find(".file-paneled").stop().animate({height: 0});
        });
    }
//添加SKU
$("#addSku").click(function(){
    $("#skuContainer").removeClass("hide");
    skuFlag=0;
    if(flag===1){
        showPic();
        flag++;
    }
    $('#skuMarketPrice').val("");
    $("#skuPrice").val("");
    $('#skuNum').val("");
    $('#skuAdv').val("");
    $('#skuType').val("");
    $("#skuPic").attr("src","img/webuploader.png").attr("data-url","").addClass("previewImg");
    previewImg();
});
//完成SKU
$("#complete").click(function(){
    var skuMarketPrice=$('#skuMarketPrice').val();
    var skuPrice=$("#skuPrice").val();
    var skuNum=$('#skuNum').val();
    var skuAdv=$('#skuAdv').val();
    var skuType=$('#skuType').val();
    var url=$("#skuPic").attr("data-url");
    if(skuMarketPrice===""||skuPrice===""||skuNum===""||skuAdv===""||skuType===""||url===""){
        layer.msg("请完整填写所有信息");
        return;
    }
    //新增Sku
    if(skuFlag===0){
        var html="<tr data-url='"+url+"' class='"+"tr"+"' data-sku=''>"
            +"<td><img src='"+changeImgUrl(url)+"'></td>"
            +"<td>"+skuMarketPrice+"</td>"
            +"<td>"+skuPrice+"</td>"
            +"<td>"+skuAdv+"</td>"
            +"<td>"+skuNum+"</td>"
            +"<td>"+skuType+"</td>"
            +"<td><div><a class='editSku'>编辑</a></div><div><a class='deleteSku'>删除</a></div></td>"
            +"</tr>";
        $("#tbody").append(html);
    }else if(skuFlag===1){
    //    编辑Sku
        var editHtml="<tr data-url='"+url+"' data-sku='"+skuId+"' class="+"tr"+">"
            +"<td><img src='"+changeImgUrl(url)+"'></td>"
            +"<td>"+skuMarketPrice+"</td>"
            +"<td>"+skuPrice+"</td>"
            +"<td>"+skuAdv+"</td>"
            +"<td>"+skuNum+"</td>"
            +"<td>"+skuType+"</td>"
            +"<td><div><a class="+'editSku'+">编辑</a></div><div><a class="+'deleteSku'+">删除</a></div></td>"
            +"</tr>";
        $($(".tr")[skuIndex]).replaceWith(editHtml);
    }
    skuBreak=1;
    $("#skuContainer").addClass("hide");
});
//编辑删除SKU
$("#tbody").on("click","a",function(){
    var tr=this.parentNode.parentNode.parentNode;
    if($(this).hasClass("deleteSku")){
        $(tr).remove();
    }else if($(this).hasClass("editSku")){
        if(flag===1){
            showPic();
            flag++;
        }
        $("#skuContainer").removeClass("hide");
        if(skuBreak==0){
            return;
        }
        skuBreak=0;
        skuFlag=1;
        skuId=$(tr).attr("data-sku");
        skuIndex=$(tr).index();
        var gsOptions=tr.lastElementChild.previousElementSibling.innerHTML;
        var AgreementPrice=tr.firstElementChild.nextElementSibling.nextElementSibling.nextElementSibling.innerHTML;
        var availableInventory=tr.lastElementChild.previousElementSibling.previousElementSibling.innerHTML;
        var retailPrice=tr.firstElementChild.nextElementSibling.nextElementSibling.innerHTML;
        var marketPrice=tr.firstElementChild.nextElementSibling.innerHTML;
        $("#skuPic").attr("src",changeImgUrl($(tr).attr("data-url"))).attr("data-url",$(tr).attr("data-url"));
        $("#skuMarketPrice").val(marketPrice);
        $("#skuPrice").val(retailPrice);
        $("#skuNum").val(availableInventory);
        $("#skuAdv").val(AgreementPrice);
        $("#skuType").val(gsOptions);
    }
});


function showPic(){
    $list3=$('#fileList3');
    // 初始化Web Uploader
    var uploader3 = WebUploader.create({

        // 选完文件后，是否自动上传。
        auto: true,

        // 文件接收服务端。
        server: web_url_prefix+'upload/uploadJitesCmsImageMulit',

        // 选择文件的按钮。可选。
        // 内部根据当前运行是创建，可能是input元素，也可能是flash.
        pick: {
            id:'#filePicker3',
            multiple:false
        },
        duplicate:true,

        // 只允许选择图片文件。
        accept: {
            title: 'Images',
            extensions: 'gif,jpg,jpeg,bmp,png',
            mimeTypes: 'image/gif,image/jpeg,image/png,image/jpg,image/bmp'
        }
    });

    //文件传输成功后的返回值
    uploader3.on("uploadAccept",function(object,ret){
        $("#skuPic").attr("src",changeImgUrl(ret.avatar)).attr("data-url",ret.avatar);
    });

    // 文件上传过程中创建进度条实时显示。
    uploader3.on( 'uploadProgress', function( file, percentage ) {
        var $li3 = $( '#'+file.id ),
            $percent = $li3.find('.progress span');

        // 避免重复创建
        if ( !$percent.length ) {
            $percent = $('<p class="progress"><span></span></p>')
                .appendTo( $li3 )
                .find('span');
        }

        $percent.css( 'width', percentage * 100 + '%' );
    });

    // 文件上传成功，给item添加成功class, 用样式标记上传成功。
    uploader3.on( 'uploadSuccess', function( file ) {
        $( '#'+file.id ).addClass('upload-state-done');
    });

    // 文件上传失败，显示上传出错。
    uploader3.on( 'uploadError', function( file ) {
        var $li3 = $( '#'+file.id ),
            $error = $li3.find('div.error');

        // 避免重复创建
        if ( !$error.length ) {
            $error = $('<div class="error"></div>').appendTo( $li3 );
        }

        $error.text('上传失败');
    });

// 完成上传完了，成功或者失败，先删除进度条。
    uploader3.on( 'uploadComplete', function( file ) {
        $( '#'+file.id ).find('.progress').remove();
    });
}